﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO.IsolatedStorage;
using TeamReview.Services;
using System.Security.Principal;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace TeamReview.Settings
{
    /// <summary>
    /// Simple xml serialization class to persist form settings
    /// </summary>
    public class SettingsReaderWriter
    {
        private TeamReviewSettings settings;
        private XmlSerializer serializer;
        private string configFile;
		private static string dataDirectory;

		public static string DataDirectory {
			get { return dataDirectory; }
			set { dataDirectory = value; }
		}


        public SettingsReaderWriter()
        {
            serializer = new XmlSerializer(typeof(TeamReviewSettings));
            configFile = Path.Combine(dataDirectory, "TeamReview.config");
            settings = ReadSettings();
        }



        public void Add(WindowSetting window)
        {
            settings.WindowSettings.Add(window);
        }

        public WindowSetting Get(string windowName)
        {
            foreach (WindowSetting ws in settings.WindowSettings)
            {
                if (ws.Name.Equals(windowName, StringComparison.InvariantCultureIgnoreCase))
                    return ws;
            }

            return null;
        }

        public void Add(TeamSetting teamSetting)
        {
            settings.TeamSettings.Add(teamSetting);
        }

        public TeamSetting Get(TeamProject project)
        {
            foreach (TeamSetting ts in settings.TeamSettings)
            {
                if (ts.ArtifactUri.Equals(project.ArtifactUri.ToString(), StringComparison.InvariantCultureIgnoreCase))
                    return ts;
            }
            return null;
        }

        public void Save()
        {
            WriteSettings();
        }

        private TeamReviewSettings ReadSettings()
        {

            if (File.Exists(configFile))
            {
                using (XmlReader reader = XmlReader.Create(configFile))
                {
                    return (TeamReviewSettings)serializer.Deserialize(reader);
                }
            }

            //empty list
            return new TeamReviewSettings();
        }


        private void WriteSettings()
        {
            using (XmlWriter writer = XmlWriter.Create(configFile))
            {
                if (writer == null)
                    throw new NullReferenceException();

                serializer.Serialize(writer, settings);

            }
        }

    }
}
